package com.yeqiangwei.commons.nimage;

import java.awt.Dimension;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import magick.ImageInfo;
import magick.MagickException;
import magick.MagickImage;

import com.yeqiangwei.commons.util.ArithHelper;
import com.yeqiangwei.commons.util.TypeChange;

public class ImageHandler {
	
	private static final Log log = LogFactory.getLog(ImageHandler.class);

	Image image;
	
	public ImageHandler(Image image) {
		this.image = image;
	}
	
	public boolean zoomOut(int w, int h, String new_path) {
		System.setProperty("jmagick.systemclassloader", "no");
		boolean bea = false;
		ImageInfo info;
		try {
			info = new ImageInfo(image.getFile().getAbsolutePath());
			MagickImage image = new MagickImage(info);
			Dimension dim = image.getDimension();
			double ow = dim.getWidth();
			double oh = dim.getHeight();
			if(w > 0 && h > 0){
				bea = resize(new_path, w, h);
			}
			else if(w == 0 && h ==0){
				/* 如果都等于0则不执行任何操作 */
			}
			else {
				if(h == 0){
					double d = ArithHelper.div(w, ow); /* 指定尺寸/源尺寸 */
					h = TypeChange.doubleToInt(ArithHelper.mul(oh, d));
				}
				else if(w == 0){
					double d = ArithHelper.div(h, oh); /* 指定尺寸/源尺寸 */
					w = TypeChange.doubleToInt(ArithHelper.mul(ow, d));
				}
				if(w <= 0){
					w = TypeChange.doubleToInt(ow);
				}
				if(h <= 0){
					w = TypeChange.doubleToInt(oh);
				}
			}
			bea = resize(new_path, w, h);
		} catch (MagickException e) {
			log.error(e);
		}
		return bea;
	}
	
	public boolean resize(String new_path, int width, int height) {
		if(log.isDebugEnabled()){
			log.debug("...... #resize(...) npath: " + new_path);
		}
		ImageInfo info;
		try {
			System.setProperty("jmagick.systemclassloader", "no");
			info = new ImageInfo(image.getFile().getAbsolutePath());
			MagickImage image = new MagickImage(info);
			MagickImage scaled = image.scaleImage(width, height);
			if(scaled == null && log.isDebugEnabled()){
				log.error("...... MagickImage is null");
			}
			// 小图片文件的大小
			scaled.setFileName(new_path);
			return scaled.writeImage(info);
		} catch (MagickException e) {
			log.error(e.toString());
		}
		return false;
	}
}
